package com.kly.smartbi.controller.bi;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kly.smartbi.common.BaseResponse;
import com.kly.smartbi.common.ErrorCode;
import com.kly.smartbi.common.ResultUtils;
import com.kly.smartbi.exception.ThrowUtils;
import com.kly.smartbi.model.dto.chat.ChatAddMessageDto;
import com.kly.smartbi.model.dto.chat.ChatQueryMessageDto;
import com.kly.smartbi.model.entity.ChatConversations;
import com.kly.smartbi.service.ChatConversationsService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author admin
 * @date 2025/3/30
 */
@RequestMapping("/chat")
@RestController
public class ChatController {

    @Resource
    private ChatConversationsService chatConversationsService;

    /**
     * ai
     *
     * @param chatAddMessageDto
     * @return
     */
    @PostMapping("/start")
    @SaCheckLogin
    public BaseResponse<String> startChat(@RequestBody ChatAddMessageDto chatAddMessageDto) {
        ThrowUtils.throwIf(ObjUtil.isNull(chatAddMessageDto), ErrorCode.PARAMS_ERROR);
        String conversation = chatConversationsService.startChat(chatAddMessageDto);
        return ResultUtils.success(conversation);
    }


    /**
     * 创建会话
     */
    @PostMapping("/create")
    @SaCheckLogin
    public BaseResponse<Long> createChat() {
        Long id = chatConversationsService.createChat();
        return ResultUtils.success(id);
    }


    /**
     * 查询已有会话
     */
    @GetMapping("/list")
    @SaCheckLogin
    public BaseResponse<Page<ChatConversations>> getChatListByPage(ChatQueryMessageDto chatQueryMessageDto) {
        int current = chatQueryMessageDto.getCurrent();
        int pageSize = chatQueryMessageDto.getPageSize();
        ThrowUtils.throwIf(ObjUtil.isNull(chatQueryMessageDto), ErrorCode.PARAMS_ERROR);
        QueryWrapper<ChatConversations> queryWrapper = chatConversationsService.getQueryWrapper(chatQueryMessageDto);
        return ResultUtils.success(chatConversationsService.page(new Page<>(current, pageSize), queryWrapper));
    }


    @PostMapping("/ai")
    public SseEmitter handleChat(@RequestBody String question) {
        SseEmitter emitter = new SseEmitter(30_000L); // 设置超时时间（毫秒）

        // 模拟AI流式响应（逐字返回）
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        executor.scheduleAtFixedRate(() -> {
            try {
                // 生成模拟的AI响应文本
                String response = "你好！我是AI助手，可以回答你的问题。";
                for (int i = 0; i < response.length(); i++) {
                    emitter.send(SseEmitter.event()
                            .name("message")
                            .data(response.substring(0, i + 1)));
                    try {
                        Thread.sleep(100); // 模拟延迟
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
                emitter.complete(); // 结束流
                executor.shutdown();
            } catch (IOException e) {
                emitter.completeWithError(e);
            }
        }, 0, 100, TimeUnit.MILLISECONDS);

        return emitter;
    }
}
